import pandas as pd
import dmPython

from manager.models import *
from django.utils.text import slugify
from django.core.management import call_command
from django.db import IntegrityError,DataError

#存储客户信息
def Client_store(dataframe,user_id='18907175979'):
    
    user_instance = Users.objects.get(username=user_id)
    num = 0

    for index,row in dataframe.iterrows():
        try:
            row_data = Client(
            name = row['客户名称'],
            clientid = row['客户编号'],
            tel = str(row['手机号']),
            addr = row['省市区'],
            user=user_instance,
            )
            row_data.save()
            num += 1
        except (IntegrityError,DataError):
            continue
    return num

#存储物流信息
def TradeInfo_store(dataframe,user_id='18907175979'):
        
    user_instance = Users.objects.get(username=user_id)
    num = 0

    for index,row in dataframe.iterrows():
        try:
            container_numbers = row['集装箱箱号'].split(',')
            row_data = TradeInfo(
            tradeid=row['提单号'],
            client=row['货主名称'],
            clientid=row['货主代码'],
            company=row['物流公司（货代）'],
            container=','.join(container_numbers),
            goods=row['货物名称'],
            weight=int(row['货重（吨）']),
            user=user_instance,
            )
            row_data.save()
            num+=1
        except Exception as err:
            # print('写入数据库异常，stores.py line72',str(err))
            continue
    return num

#存储物流公司信息
def TradeCompany_store(dataframe,user_id='18907175979'):
    
    num = 0
    user_instance = Users.objects.get(username=user_id)
   
    for index,row in dataframe.iterrows():
        try:
            row_data = TradeCompany(
            company=row['公司名称'],
            clientid =row['客户编号'],
            admin=row['联系人'],
            tel=row['电话'],
            area=row['省市区'],
            user = user_instance
            )
            row_data.save()
            num+=1
        except (IntegrityError,DataError):
            continue
    return num

#存储装货表
def Ship_store(dataframe,user_id='18907175979'):
    
    num = 0
    user_instance = Users.objects.get(username=user_id)

    for index,row in dataframe.iterrows():
        try:
            container_numbers = row['集装箱箱号'].split(',')
            row_data = Ship(
            company = row['船公司'],
            shipname = row['船名称'],
            btime = row['作业开始时间'],
            etime = row['作业结束时间'],
            gotime = row['始发时间'],
            artime = row['到达时间'],
            harbor = row['作业港口'],
            sid = row['提单号'],
            con_id = ','.join(container_numbers),
            size = int(row['箱尺寸（TEU）']),
            source = row['启运地'],
            destination = row['目的地'],
            user=user_instance,
            )
            row_data.save()
            num+=1
        except (IntegrityError,DataError):
            continue
    return num

#存储卸货表
def Unship_store(dataframe,user_id='18907175979'):
    
    num = 0
    user_instance = Users.objects.get(username=user_id)

    for index,row in dataframe.iterrows():
        try:
            container_numbers = row['集装箱箱号'].split(',')
            row_data = Unship(
            company = row['船公司'],
            shipname = row['船名称'],
            btime = row['作业开始时间'],
            etime = row['作业结束时间'],
            gotime = row['始发时间'],
            artime = row['到达时间'],
            harbor = row['作业港口'],
            sid = row['提单号'],
            con_id = ','.join(container_numbers),
            size = int(row['箱尺寸（TEU）']),
            source = row['启运地'],
            destination = row['目的地'],
            user=user_instance,
            )
            row_data.save()
            num+=1
        except (IntegrityError,DataError):
            continue
    return num

#存集装箱动态表
def container_store(dataframe,user_id='18907175979'):
    
    num = 0
    user_instance = Users.objects.get(username=user_id)

    for index,row in dataframe.iterrows():
        try:
            row_data = Container(
            harbor = row['堆存港口'],
            con_id = row['集装箱箱号'],
            size = row['箱尺寸（TEU）'],
            sid = row['提单号'],
            store = row['堆场位置'],
            op = row['操作'],
            opdata = row['操作日期'],
            user=user_instance,
            )
            row_data.save()
            num+=1
        except (IntegrityError,DataError) as err:
            continue
    return num

#动态创建model
def create_dynamic_model(df, table_name):
    # 将表名转换为合法的数据库表名
    table_name = slugify(table_name)

    # 动态设置模型类的Meta属性，包括表名
    meta = type('Meta', (), {'db_table': table_name})
    attrs = {'__module__': __name__, 'Meta': meta}
    model_name = f'DynamicModel_{table_name}'
    dynamic_model_class = type(model_name, (models.Model,), attrs)
    #dynamic_model_class = type(model_name, (DynamicModel,), attrs)

    # 获取动态模型类的字段名称列表
    column_names = df.columns.tolist()

    # 动态为模型类添加字段
    for column_name in column_names:
        field = models.CharField(max_length=20)  # 根据实际需求选择合适的字段类型
        field.contribute_to_class(dynamic_model_class, column_name)

    # 返回动态模型类
    return dynamic_model_class

#数据库迁移
def generate_and_apply_migrations():
    call_command('makemigrations', 'manager', interactive=False)
    call_command('migrate', 'manager', interactive=False)


